package com.gitee.wsl.struct.generator.sample

import com.gitee.wsl.time.toLocalDateTime
import kotlin.random.Random
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue


/**
 * 店铺卡号生成器单元测试
 *
 * @author liuzhaoming
 * @date 2017/11/23
 * @see ShopCardIdGenerator
 */
class ShopCardIdGeneratorTest {
    private val cardIdGenerator: ShopCardIdGenerator = ShopCardIdGenerator()

    @Test
    fun generate() {
        val id: Long = cardIdGenerator.generate("A00001")
        assertEquals(16, id.toString().length)
    }

    @Test
    fun validate() {
        val shopId = "A00001"
        var id: Long = cardIdGenerator.generate(shopId)
        assertTrue(cardIdGenerator.validate(shopId, id))
        assertFalse(cardIdGenerator.validate(shopId, ++id))
        assertFalse(cardIdGenerator.validate("A000111", id))
    }

    @Test
    fun parse() {
        val shopId = "A1234567"
        val id: Long = cardIdGenerator.generate(shopId)
        val results: Array<Long> = cardIdGenerator.parse(id)!!

        val timestamp = results[0]
        val dateTime = timestamp.toLocalDateTime()
        println("Time: $dateTime")
        println("Machine id: " + results[1])
        println("Sequence: " + results[2])
    }

    @Test
    fun performance() {
        val shopId = "A00001"
        val num: Long = 100
        for (i in 0 until num) {
            val id: Long = cardIdGenerator.generate(shopId)
            println(id)
        }
    }

    @Test
    fun crash() {
        val shopId = "A00001"
        val num: Long = 10000000
        var passNum: Long = 0

        for (i in 0 until num) {
            val sb = StringBuilder()
            for (j in 0..15) {
                sb.append(Random.nextInt(100) / 10)
            }

            val id: Long = sb.toString().toLong()
            if (cardIdGenerator.validate(shopId, id)) {
                passNum++
            }
        }

        println(passNum)
    }

    @Test
    fun crash1() {
        val shopId = "A00001"
        val num: Long = 100000000
        var passNum: Long = 0
        var id: Long = cardIdGenerator.generate(shopId)
        for (i in 0 until num) {
            if (cardIdGenerator.validate(shopId, ++id)) {
                passNum++
            }
        }

        println(passNum)
    }
}